//
//  ViewController.m
//  WhatWeather
//
//  Created by byn on 15/10/10.
//  Copyright © 2015年 byn. All rights reserved.
//

#import "ShowDetailWeatherTVC.h"
#import "WWWeatherAPI.h"
#import "WWCommonUtility.h"
#import "WWAreadIdBridge.h"
#import "WWAreaInfo.h"
#import "FileUtil.h"
#import "MJRefresh.h"
#import "WWWeatherInfo.h"
#import "WWTodayWeatherInfoCollectionViewCell.h"
#import "WWDailyForecastCollectionViewCell.h"
#import "WWCollectedCitiesManage.h"

@interface ShowDetailWeatherTVC ()
@property (nonatomic ,strong) WWWeatherInfo *weatherInfo;
@end

@implementation ShowDetailWeatherTVC

NSString * fileName = @"test.plist";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"WeatherToday" bundle:nil] forCellWithReuseIdentifier:@"WeatherToday"];
    [_collectionView registerNib:[UINib nibWithNibName:@"WeatherDaily" bundle:nil] forCellWithReuseIdentifier:@"WeatherDaily"];
    [_collectionView reloadData];
    UIImage *img = [UIImage imageNamed:@"blue_mask.png"];
    UIImageView *bgImageView = [[UIImageView alloc] initWithImage:img];
    bgImageView.frame = CGRectMake(0, 0, self.backView.frame.size.width, self.backView.frame.size.height);
        //[_backView addSubview:bgImageView];
    [_backView setBackgroundColor:[UIColor colorWithPatternImage:img]];
    [FileUtil createFileInPath:fileName];
    self.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        __unsafe_unretained __typeof(self) weakSelf = self;
        [weakSelf reqForWeather];
    }];
    NSString *curSelCity = [[WWCollectedCitiesManage sharedCollectedCities] getCurSelCityId];
    if (!curSelCity) {
        
        _locationManager = [[WWLocationManager alloc] init];
        [_locationManager updateLocation:^(NSString *cityName) {
            
            NSLog(@"cityname = %@",cityName);
            WWAreadIdBridge *areaBridge = [WWAreadIdBridge getInstance];
            NSString *finalCityName = [areaBridge getFinalString:cityName];
            NSArray *array = [areaBridge queryDataWithSearchText:finalCityName.mutableCopy searchPattern:SearchPatternMatch];
            if(array != nil) {
                WWAreaInfo *areaInfo = (WWAreaInfo *)[array firstObject];
                NSLog(@"cityid = %@",areaInfo.areaId);
                _curAreaId = areaInfo.areaId;
                [[WWCollectedCitiesManage sharedCollectedCities] addNewCity:areaInfo.areaId cityName:areaInfo.nameCN];
                [[WWCollectedCitiesManage sharedCollectedCities] addCurSelCity:areaInfo.areaId];
            }
            
            [self.scrollView.mj_header beginRefreshing];
        }];

    } else {
        _curAreaId = curSelCity;
        [self startReqWeatherDirectly];
    }
}

- (void) startReqWeatherDirectly {
    [self showHistoryWeather];
    [self.scrollView.mj_header beginRefreshing];
    [self reqForWeather];
}

- (void)showHistoryWeather {
    if (nil != _historyWeather) {
        NSError *error = [[NSError alloc] init];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[_historyWeather dataUsingEncoding:NSUTF8StringEncoding]  options:NSJSONReadingMutableLeaves error:&error];
        if (nil != dic) {
            [self.weatherInfo setupWeatherInfo:dic];
            [self.collectionView reloadData];
        }
    }
}

- (void) reqForWeather{
    if ([self isNeedReqWeather]){
        WWWeatherAPI *weatherAPI = [[WWWeatherAPI alloc] init];
        [weatherAPI ReqForNormalWeather:_curAreaId sucBlock: ^(id responseObject, NSString *responseString){
            NSLog(@"%@",responseObject);
            __unsafe_unretained __typeof(self) weakSelf = self;
            if (weakSelf.weatherInfo == nil) {
                weakSelf.weatherInfo = [[WWWeatherInfo alloc] init];
            }
            [weakSelf.weatherInfo setupWeatherInfo:responseObject];
            [weakSelf showDataInfo];
            [weakSelf.collectionView reloadData];
            [weakSelf.scrollView.mj_header endRefreshing];
            [[WWCollectedCitiesManage sharedCollectedCities] setCityWeather:responseString withCityId:weakSelf.weatherInfo.cityId];
        }];
    }
    else{
        NSString *filePath = [FileUtil getFilePathByFileName:fileName];
        NSDictionary *fileContent = [[NSDictionary alloc] initWithContentsOfFile:filePath];
            //[self getDataFromJson:fileContent];
        [self showDataInfo];
    }

}

/**
 *  是否需要请求天气
 *
 *  @return <#return value description#>
 */
- (BOOL) isNeedReqWeather{
    BOOL bReq = YES;
    return bReq;
}

- (void)showDataInfo {
    NSString *city = _weatherInfo.city;
    self.navigationItem.title = city;
}


- (void)pushSearchView{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    [self.navigationController pushViewController:[storyboard instantiateViewControllerWithIdentifier:@"searchView"] animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sendChangeLocation:(id)sender {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 2;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    return CGSizeMake(_collectionView.frame.size.width, height);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
        case 0: {
            WWTodayWeatherInfoCollectionViewCell *cell = (WWTodayWeatherInfoCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"WeatherToday" forIndexPath:indexPath];
            [cell configureCell:_weatherInfo];
            return cell;
        }
            break;
        case 1: {
            WWDailyForecastCollectionViewCell *cell = (WWDailyForecastCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"WeatherDaily" forIndexPath:indexPath];
            [cell configureCell:_weatherInfo];
            return cell;
        }
            break;
        default:
            break;
    }
    return nil;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0.0;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0.0;
}

@end



















